package com.atguigu.activemq.topic;

import lombok.SneakyThrows;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @Auther 赵乾坤
 * @Date 2021-04-15 23:48
 */
public class JmsConsumer_Topic {
    public static final String ACTIVEMQ_URL = "tcp://192.168.200.128:61616";//根据自己的虚拟机写
    public static final String TOP_NAME = "topic-atguigu";

    public static void main(String[] args) throws JMSException, IOException {

        System.out.println("*******我是3号消费者");

        //1.创建连接工场，按照给定的url地址，采用默认用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工场，获取连接connection并启动访问
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        //3 创建会话session
        //两个参数，第一个叫事务/第二个叫签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //4 创建目的地（具体是队列还是主题topic）
        Topic topic = session.createTopic(TOP_NAME);
        //5.创建消费者
        MessageConsumer messageConsumer = session.createConsumer(topic);


        //通过监听的方式来消息消息    MessageConsumer messageConsumer = session.createConsumer(queue);
      messageConsumer.setMessageListener((message -> {//通过lomb 写消息
          if (null != message && message instanceof TextMessage) {
              TextMessage textMessage = (TextMessage) message;//用什么发送用什么接受
              try {
                  System.out.println("*********消费者接受到Topic消息：" + textMessage.getText());
              } catch (JMSException e) {
                  e.printStackTrace();
              }
          }
      }));



        System.in.read();
        messageConsumer.close();
        session.close();
        connection.close();

    }

}
